﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;

namespace hms.azureutillibrary.common
{
    public class BlobHandler
    {
        private CloudBlobClient _cloudBlobClient;

        public BlobHandler(CloudBlobClient cloudBlobClient)
        {
            if (cloudBlobClient == null)
                throw new ArgumentNullException("cloudBlobClient");
            
            _cloudBlobClient = cloudBlobClient;         
        }

        public async Task<int> CountOfItems(string blobContainerName, bool useFlatBlobListing =  false)
        {
            int itemCount = 0;

            CloudBlobContainer cloudBlobContainer = _cloudBlobClient.GetContainerReference(blobContainerName);

            foreach (var blobItem in cloudBlobContainer.ListBlobs(null,useFlatBlobListing,BlobListingDetails.None,null,null))
            {
                itemCount++;
            }

            return itemCount;
        }

        public async Task<Dictionary<string, int>> CountOfItemsByExtension(string blobContainerName, bool useFlatBlobListing = false)
        {
            var itemCountDic = new Dictionary<string, int>();
            string ext = "";

            CloudBlobContainer cloudBlobContainer = _cloudBlobClient.GetContainerReference(blobContainerName);

            foreach (var blobItem in cloudBlobContainer.ListBlobs(null, useFlatBlobListing, BlobListingDetails.None, null, null))
            {
                ext = blobItem.Uri.ToString().Substring(blobItem.Uri.ToString().LastIndexOf('.'));
                if (itemCountDic.ContainsKey(ext))
                {
                    itemCountDic[ext] = itemCountDic[ext] + 1;
                }
                else
                {
                    itemCountDic.Add(ext , 1);
                }
            }

            return itemCountDic;
        }
 

    }
}